package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.Path}")
    private String parentPath;

    @PostMapping("/upload")
    public R<String> Upload(MultipartFile file) {
        String s = UUID.randomUUID().toString();
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = s + substring;

        File file1 = new File(parentPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        log.info(file.getOriginalFilename());
        try {
            file.transferTo(new File(parentPath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, String name){
        try {
            FileInputStream fis=new FileInputStream(new File(parentPath+name));
            byte[] bytes=new byte[1024];
            ServletOutputStream outputStream = response.getOutputStream();
            int len;
            response.setContentType("image/jpeg");
            while ((len=fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
